package com.gccloud.tgyfirst.controller.demo;

import com.gccloud.tgyfirst.demo.dto.CourseDTO;
import com.gccloud.tgyfirst.demo.entity.CourseEntity;
import com.gccloud.tgyfirst.service.demo.service.ICourseService;
import com.gccloud.tgyfirst.service.demo.service.IImportAndExportService;

import cn.afterturn.easypoi.entity.vo.MapExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSON;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.utils.BeanConvertUtils;
import com.gccloud.starter.common.vo.R;
import com.gccloud.starter.core.controller.SuperController;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiSort;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author qianxing
 * @version 1.0
 * @date 2021/5/19 9:51
 */
@RestController
/**
 * 定义在swagger中展示导入导出模块，并且它的接口排序为 50
 */
@Api(tags = "导入导出")
@ApiSort(value = 50)
public class ImportAndExportController  extends SuperController {
    @Resource
    private ICourseService courseService;

    @Resource
    private IImportAndExportService iImportAndExportService;

    @GetMapping("/export")
    @ApiOperation(value = "导出所有课程", notes = "导出课程", produces = MediaType.APPLICATION_JSON_VALUE)
    public void export(HttpServletResponse response, HttpServletRequest request, ModelMap map) {
        List<ExcelExportEntity> entity = Lists.newArrayList();
        Class clazz = CourseDTO.class;
        for (; clazz != Object.class; clazz = clazz.getSuperclass()){
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                ExcelExportEntity excelEntity =  new ExcelExportEntity(f.getName(), f.getName(), 20);
                entity.add(excelEntity);
            }
        }
        // 构建一个List存储map
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CourseEntity> courseEntityList =  courseService.list();
        courseEntityList.forEach(item -> {
            // put的name对应上面创建的ExcelExportEntity的key
            // tmap相当于excel表格的一行内容
            CourseDTO courseDTO = BeanConvertUtils.convert(item, CourseDTO.class);
            Map<String,Object> tmap = JSON.parseObject(JSON.toJSONString(courseDTO),Map.class);
            // 格式化日期时间
            Date date = new Date();
            date.setTime((long) tmap.get("startDate"));
            tmap.put("startDate", sdf.format(date));
            date.setTime((long) tmap.get("endDate"));
            tmap.put("endDate", sdf.format(date));
            // 将数据存到List中
            list.add(tmap);
        });
        // 创建导出参数
        ExportParams params = new ExportParams("课程信息列表", "课程信息列表", ExcelType.XSSF);
        // 指定要导出的List集合数据
        map.put(MapExcelConstants.MAP_LIST, list);
        // 指定ExcelExportEntity
        map.put(MapExcelConstants.ENTITY_LIST, entity);
        // 指定要导出的参数
        map.put(MapExcelConstants.PARAMS, params);
        // 文件名
        map.put(MapExcelConstants.FILE_NAME, "课程信息列表");
        PoiBaseView.render(map, request, response, MapExcelConstants.EASYPOI_MAP_EXCEL_VIEW);
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入", notes = "导入课程", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Void> importFromExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String fileName = file.getOriginalFilename();
        // 上传文件为空
        if (StringUtils.isEmpty(fileName)) {
            throw new GlobalException("没有导入文件");
        }
        String extension = FilenameUtils.getExtension(fileName);
        // 上传文件名格式不正确
        if (!"xlsx".equals(extension)) {
            throw new GlobalException("文件名格式不正确, 请使用后缀名为.xlsx的文件");
        }
        DateConverter converter = new DateConverter();
        converter.setPattern("yyyy-MM-dd HH:mm:ss");
        ConvertUtils.register(converter, Date.class);
        iImportAndExportService.importFromExcel(file.getInputStream());
        return success();
    }
}
